// import { WebVariable } from "../../data/WebVariable";
import { getUserInfo } from "../../utils/common";
import { AjaxData } from "../../data/interface/publicInterface";
import { message } from "antd";
let interceptors_res: any = [
  async (res: any) => {
    let ss: AjaxData = await res.json();
    if (!ss.success) {
      message.error(ss.message);
    }
    return ss;
  },
];
let interceptorsFile_res: any = [
  async (res: any) => {
    let ss = await res.blob();
    return ss;
  },
];
export class HttpClient {
  private constructor() {}

  fetch(url: RequestInfo, init: RequestInit | undefined): Promise<Response> {
    let headers: any = "";
    if (typeof init != "undefined") {
      if (init.headers) {
        init.headers["Content-Type"] = "application/json";
        Object.assign(init.headers, this.getHeaders());
      }
      headers = init.headers;
    }

    return new Promise(function (resolve, reject) {
      //发起fetch请求，fetch请求的形参是接收上层函数的形参
      fetch(url, init)
        .then((res) => {
          //interceptors_res是拦截响应结果的拦截处理函数集合
          if (headers) {
            switch (headers["qingqiuType"]) {
              case "file":
                //文件下载使用
                interceptorsFile_res.forEach((interceptors: any) => {
                  //拦截器对响应结果做处理，把处理后的结果返回给响应结果。
                  res = interceptors(res);
                });
                break;

              default:
                //正常拦截
                interceptors_res.forEach((interceptors: any) => {
                  //拦截器对响应结果做处理，把处理后的结果返回给响应结果。
                  res = interceptors(res);
                });
                break;
            }
          } else {
            //正常拦截
            interceptors_res.forEach((interceptors: any) => {
              //拦截器对响应结果做处理，把处理后的结果返回给响应结果。
              res = interceptors(res);
            });
          }

          //将拦截器处理后的响应结果resolve出去
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  protected getHeaders() {
    const data: IHttpHeader = {
      // "Content-Type": this.contentType,
      Authorization: getUserInfo("randomData"),
      i18n: "zh",
    };
    return data;
  }

  static instance() {
    return new HttpClient();
  }
}

export interface IHttpHeader {
  [key: string]: string;
}
